package multimedia;

import java.io.ByteArrayOutputStream;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.media.control.RecordControl;

import ui.VadeMecumCameraCanvas;
import ui.VadeMecumVideoViewer;

public class StopRecordThread implements Runnable, CommandListener {

	private VadeMecumCameraCanvas canvas;
	
	private VadeMecumVideoViewer viewer;
	
	private ByteArrayOutputStream videoStream;
	
	public StopRecordThread(VadeMecumCameraCanvas canvas, ByteArrayOutputStream videoStream) {
		this.canvas = canvas;
		this.videoStream = videoStream;
	}
	
	public void run() {
		if (canvas.isRecording()) {
			try {
				RecordControl rc = canvas.getRecordControl();
				rc.stopRecord();
				rc.commit();				
				
				//exibe o video e mostra as opcoes
				viewer = new VadeMecumVideoViewer(canvas.midlet, videoStream.toByteArray());			
				viewer.setCommandListener(this);
				
				canvas.midlet.display.setCurrent(viewer);				

				canvas.setRecording(false);
				canvas.removeCommand(canvas.stopRecording);
				canvas.addCommand(canvas.initRecording);
			} catch (Exception e) {
				canvas.midlet.error(e);
			}
		} else {			
			canvas.midlet.error(new Exception("Is not recording!"));		
		}
	}

	public void commandAction(Command cmd, Displayable disp) {
		if(viewer.cmdRepeat == cmd) {
			viewer.repaint();
			viewer.repeat();
		} else if(viewer.cmdContinue == cmd) {
//			viewer.closeStreams();
		} else if(viewer.cmdBack == cmd) {
			viewer.closeStreams();
			canvas.midlet.display.setCurrent(canvas);
		} else if (viewer.stop == cmd) {
			viewer.stop();
		} else if (viewer.play == cmd) {
			viewer.play();
		} else if (viewer.repeat == cmd) {
			viewer.repeat();
		} else if (cmd == viewer.save) {
			viewer.saveSnapshot();
		} else if (cmd == viewer.sendToServiceWhithoutContext) {
			viewer.sendWithoutContext();
		} else if (cmd == viewer.sendToServiceWithContext) {
			viewer.sendWithContext();
		}
	}	

}
